package js.web.center.creater;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

import js.web.center.creater.vo.JsWebDatabaseCreaterVo;
import js.web.center.database.JsWebMySql;

/**
 * 数据库接口生成工具
 * @author qpduw
 *
 */
public class JsWebDatabaseCreater {
	private static Logger logger=Logger.getLogger(JsWebDatabaseCreater.class);
	private String fileName=null;
	private String path=null;
	private ArrayList<String> saveFuns=new ArrayList<>();
	public JsWebDatabaseCreater(String path,String fileName){
		this.fileName=fileName;
		this.path=path;
	}
	/**
	 * 保存文件
	 * @throws IOException
	 */
	public void save() throws IOException{
		File file=new File(this.path+"/"+this.fileName+".js");
		String oldInfo="";
		if(file.exists()){
			FileInputStream fileInputStream=new FileInputStream(file);
			byte[] reads=new byte[fileInputStream.available()];
			fileInputStream.read(reads);
			oldInfo=new String(reads);
			fileInputStream.close();
			file.delete();
		}
		FileOutputStream outputStream=new FileOutputStream(file);
		if(oldInfo.length()<1){
			oldInfo="var "+getClassName()+"={};\nvar D=DATA_BASE_TYPE;";
		}
		for (String saveFun : saveFuns) {
			oldInfo+="\n"+saveFun;
		}
		outputStream.write(oldInfo.getBytes());
		outputStream.flush();
		outputStream.close();
	}
	private String getClassName(){
		return this.fileName+"Utils";
	}
	/**
	 * 获取表的数据信息
	 * @param table 表名
	 * @return
	 */
	private static HashMap<String, JsWebDatabaseCreaterVo> createTableTypes(String table){
		Connection connection = null;
		String sql="desc "+table;
		HashMap<String, JsWebDatabaseCreaterVo> tableTypes=new HashMap<>();
		try{
			connection = JsWebMySql.getInstance().getConnection();
			PreparedStatement prepareStatement = connection.prepareStatement(sql);
			ResultSet executeQuery = prepareStatement.executeQuery();
			while(executeQuery.next()){
				JsWebDatabaseCreaterVo createrVo=new JsWebDatabaseCreaterVo();
				createrVo.setField(executeQuery.getNString("Field"));
				createrVo.setDefault(executeQuery.getNString("Default"));
				createrVo.setExtra(executeQuery.getNString("Extra"));
				createrVo.setKey(executeQuery.getNString("Key"));
				createrVo.setNull(executeQuery.getNString("Null"));
				createrVo.setType(executeQuery.getNString("Type"));
				tableTypes.put(executeQuery.getString("Field"), createrVo);
			}
			executeQuery.close();
			prepareStatement.close();
		}catch(Exception e){
			logger.error("JsWebDatabaseCreater ERROR:{}",e);
		}finally{
			if(connection!=null){
				try {
					connection.close();
				} catch (SQLException e) {
					logger.error("JsWebDatabaseCreater ERROR:{}",e);
				}
			}
		}
		return tableTypes;
	}
	/**
	 * 生成处理类型
	 * @param createrVo
	 * @return
	 * @throws Exception
	 */
	private static String getType(JsWebDatabaseCreaterVo createrVo) throws Exception{
		String type = createrVo.getType();
		if(type.indexOf("int")>-1){
			return "D.INT";
		}else if(type.indexOf("varchar")>-1||type.indexOf("text")>-1){
			return "D.STRING";
		}else if(type.indexOf("long")>-1){
			return "D.LONG";
		}else if(type.indexOf("short")>-1){
			return "D.SHORT";
		}else if(type.indexOf("double")>-1){
			return "D.DOUBLE";
		}else if(type.indexOf("bool")>-1){
			return "D.BOOLEAN";
		}else if(type.indexOf("date")>-1){
			return "D.DATE";
		}else if(type.indexOf("timestamp")>-1){
			return "D.TIMESTAMP";
		}else if(type.indexOf("bigdecimal")>-1){
			return "D.BIGDECIMAL";
		}else if(type.indexOf("float")>-1){
			return "D.FLOAT";
		}else{
			throw new Exception("类型错误");
		}
	}
	/**
	 * 生成插入接口
	 * @param table 表名
	 * @param funName 方法名
	 * @param keys 插入键
	 * @param back 是否需要返回值
	 * @throws Exception 
	 */
	public void sqlInsert(String table,String funName,ArrayList<String> keys,boolean back) throws Exception{
		String createStr=getClassName()+"."+funName+"=function(){\n";
		String sql="";
		sql="insert into "+table+"(";
		String insertSql=") values(";
		String params="[";
		HashMap<String, JsWebDatabaseCreaterVo> tableTypes=createTableTypes(table);
		for(int i=0;i<keys.size();i++){
			sql+="";
			JsWebDatabaseCreaterVo jsWebDatabaseCreaterVo = tableTypes.get(keys.get(i));
			if(i==keys.size()-1){
				insertSql+="?)";
				params+="{value:"+keys.get(i)+",type:"+getType(jsWebDatabaseCreaterVo)+"}";
			}else{
				insertSql+="?,";
				params+=",{value:"+keys.get(i)+",type:"+getType(jsWebDatabaseCreaterVo)+"}";
			}
		}
		params+="]";
		sql=sql+insertSql;//最终形成sql
		String runUtils="\nreturn RunDataBase.queryBackInsert("+sql+","+params+","+(back?"true":"false")+")";
		createStr+=runUtils+"\n}";
		saveFuns.add(createStr);
	}
	/**
	 * 生成更新接口
	 * @param table 表名
	 * @param funName 方法名
	 * @param updates 更新值
	 * @param conditions 更新条件
	 * @param whereStr 条件语句
	 * @throws Exception 
	 */
	public void sqlUpdate(String table,String funName,ArrayList<String> updates,ArrayList<String> conditions,String whereStr) throws Exception{
//		HashMap<String,JsWebDatabaseCreaterVo> tableTypes = createTableTypes(table);
//		String createStr=getClassName()+"."+funName+"=function(){\n";
//		String sql="update "+table+" set ";
//		String params="[";
//		for(int i=0;i<updates.size();i++){
//			String field = updates.get(i);
//			JsWebDatabaseCreaterVo jsWebDatabaseCreaterVo = tableTypes.get(field);
//			String type = getType(jsWebDatabaseCreaterVo);
//			if(params.equals("[")){
//				params+="{value:"+field+",type:"+type+"}";
//			}else{
//				params+=",{value:"+field+",type:"+type+"}";
//			}
//			sql+=field+"=?";
//			if(i>0){
//				sql+=","+field+"=?";
//			}
//		}
//		for(int i=0;i<conditions.size();i++){
//			if(params.equals("[")){
//				String condition = conditions.get(i);
//				JsWebDatabaseCreaterVo jsWebDatabaseCreaterVo = tableTypes.get(condition);
//				getType(createrVo)
//				params+="{value:"+condition+",type:"++"}";
//			}
//		}
//		if(whereStr.length()>0){
//			sql+=" where "+whereStr;
//		}
//		
	}
	/**
	 * 多sql更新
	 * @param tables 多表
	 * @param updates 多更新参数
	 * @param conditions 多更新条件
	 */
	public void sqlsUpdate(ArrayList<String> tables,ArrayList<ArrayList<String>> updates,ArrayList<ArrayList<String>> conditions){
		
	}
	/**
	 * 生成对象查询
	 * @param table 表名
	 * @param sql 查询语句
	 * @param conditions 查询参数
	 */
	public JSONObject sqlGetObject(String table,String sql,ArrayList<String> conditions){
		return null;
	}
	/**
	 * 生成分页查询
	 * @param table 表名
	 * @param sql sql语句
	 * @param page 页数
	 * @param pageNum 页显示数
	 * @param conditions 查询条件
	 * @return
	 */
	public JSONObject sqlGetObjectPageList(String table,String sql,int page,int pageNum,ArrayList<String> conditions){
		return null;
	}
	/**
	 * 生成列表查询
	 * @param table 表名
	 * @param sql sql语句
	 * @param conditions 查询条件
	 * @return
	 */
	public JSONObject sqlGetObjectList(String table,String sql,ArrayList<String> conditions){
		return null;
	}
	/**
	 * 删除指定对象
	 * @param table 表名
	 * @param sql sql语句
	 * @param conditions 删除条件
	 */
	public void delObject(String table,String sql,ArrayList<String> conditions){
		
	}
}
